<?php

namespace app\admin\controller;

use app\admin\model\Marking;
use think\db\Where;

class Statistics extends Backend
{
    protected $type;

    protected $day;

    /**
     * 初始化方法
     *
     * @author 牧羊人
     * @since  : 2023/09/16
     */
    public function initialize()
    {
        parent::initialize();
        $this->type  = $this->request->param('type');
        $this->model = \app\admin\model\Operation::where('mark', 1);
        $this->day   = 0;
    }


    //
    public function getData()
    {
        $foundation = $this->foundation();
        $cake       = $this->cake();
        $column     = $this->column();
        $fold_line  = $this->fold_line();
        $data       = [
            'cake'       => $cake,
            'foundation' => $foundation,
            'column'     => $column,
            'fold_line'  => $fold_line
        ];

        return $this->jsonReturn(message('', true, $data));
    }

    public function getMapData()
    {
        $param  = request()->param();
        $street = null;
        $cityCode = 440309;
        if (!empty($param['cityValue'])) {
            //$cityCode = \app\admin\model\City::getCodeByName($param['cityValue']);
            $cityCode = (int)end($param['cityValue']);
        }
        if (!empty($param['lnglat'])) {
            $street = (new \app\admin\model\Street())->getInfoByGrid(
                $param['lnglat'][0],
                $param['lnglat'][1],
                ['id', 'ST_AsText(polygon) polygon', 'center']
            );
        }
        if (!empty($param['street_id'])) {
            $street = (new \app\admin\model\Street())
                ->where('id', $param['street_id'])
                ->field(['id', 'ST_AsText(polygon) polygon', 'center'])
                ->find();
        }
        if ($street) {
            $street             = $street->toArray();
            $street['center']   = $street['center'] ? json_decode($street['center'], true) : '';
            $street['polygon']  = polygon2geo($street['polygon']);
            $street['children'] = (new \app\admin\model\Street())
                ->where('pid', $street['id'])
                ->column('ST_AsText(polygon)');
            foreach ($street['children'] as &$v) {
                $v = polygon2geo($v);
            }
            unset($v);
        }
        $list    = (clone $this->model)
            ->where('mark', 1)
            ->with(
                [
                    'unit'     => function ($query) {
                        $query->field('id, unit_name');
                    },
                    'abnormal' => function ($query) {
                        $query->field('id, name');
                    },
                    'user'     => function ($query) {
                        $query->field('id, realname');
                    }
                ]
            )
            ->where(['type' => $this->type])
            ->where(
                function ($query) use ($param, $street, $cityCode) {
                    if (!empty($param['start_time']) && !empty($param['end_time'])) {
                        $start_time = strtotime($param['start_time']);
                        $end_time   = strtotime($param['end_time']) + 3600 * 24 - 1;
                        $query->whereBetween('create_time', [$start_time, $end_time]);
                    }
                    if (!empty($param['cityValue'])) {
                        $query->where('area_id', $cityCode);
                    }
                    if (!empty($param['operation_category'])) {
                        $query->where('operation_category', $param['operation_category']);
                    }
                    if ($street) {
                        $query->where('street_id', $street['id']);
                    }
                }
            )
            ->select();
//        $countys = [];
        foreach ($list as &$val) {
//            $countys[]                      = $val['area_id'];
            $val['organization_name']       = $val['unit']['unit_name'];
            $val['exception_category_name'] = $val['abnormal']['name'];
            $val['create_user']             = $val['user']['realname'];
            $val['operation_category_name'] = $val['operation_category_name'];
            $val['images']                  = $val['images'] ? json_decode($val['images'], true) : [];
        }
//        if (empty($param['cityValue'])) {
//            $district = \app\admin\model\City::whereIn('citycode', $countys)->column('name');
//        }
        $district = [\app\admin\model\City::getNameByCode($cityCode)];
        if (empty($street)) {
            $street = (new \app\admin\model\Street())
                ->where('pid', 0)
                ->where('district', $cityCode)
                ->column('ST_AsText(polygon) polygon');
            foreach ($street as &$v) {
                $v = polygon2geo($v);
            }
            $street['polygon'] = $street;
            $street['center'] = '';
        }
        $data     = [
            'list'     => $list,
            'polygon'  => $street,
            'district' => $district
        ];

        return $this->jsonReturn(message('', true, $data));
    }

    public function getCategoryData()
    {
        $data        = request()->param();
        $datas        = (clone $this->model)->where(['type' => $this->type])
            ->where(
                function ($query) use ($data) {
                    if (!empty($data['start_time']) && !empty($data['end_time'])) {
                        $start_time = strtotime($data['start_time']);
                        $end_time   = strtotime($data['end_time']) + 3600 * 24 - 1;
                        $query->whereBetween('create_time', [$start_time, $end_time]);
                    }
                    if (!empty($data['citycode'])) {
                        $query->where(['area_id' => end($data['citycode'])]);
                    }
                    if (!empty($data['street_id'])) {
                        $query->where(['street_id' => $data['street_id']]);
                    }
                    if (!empty($data['exception_category'])) {
                        $query->where(['exception_category' => $data['exception_category']]);
                    }
                }
            )->group('street_id')->column('street_id');
        $streetModel = new \app\admin\model\Street();
        $streetData  = $streetModel->whereIn('id', implode(',', $datas))->select();
        $newdata     = [];
        foreach ($streetData as $key => $value) {
            //异常标记数量
            $yccount = (clone $this->model)
                ->where(['type' => $this->type])
                ->where(
                    function ($query) use ($data) {
                        if (!empty($data['start_time']) && !empty($data['end_time'])) {
                            $start_time = strtotime($data['start_time']);
                            $end_time   = strtotime($data['end_time']) + 3600 * 24 - 1;
                            $query->whereBetween('create_time', [$start_time, $end_time]);
                        }
                        if (!empty($data['citycode'])) {
                            $query->where(['area_id' => end($data['citycode'])]);
                        }
                        if (!empty($data['street_id'])) {
                            $query->where(['street_id' => $data['street_id']]);
                        }
                        if (!empty($data['exception_category'])) {
                            $query->where(['exception_category' => $data['exception_category']]);
                        }
                    }
                )
                ->where(['street_id' => $value['id']])
                ->where(['operation_category' => 1])->count();
            //正常标记数量
            $zccount = (clone $this->model)
                ->where(['type' => $this->type])
                ->where(
                    function ($query) use ($data) {
                        if (!empty($data['start_time']) && !empty($data['end_time'])) {
                            $start_time = strtotime($data['start_time']);
                            $end_time   = strtotime($data['end_time']) + 3600 * 24 - 1;
                            $query->whereBetween('create_time', [$start_time, $end_time]);
                        }
                        if (!empty($data['citycode'])) {
                            $query->where(['area_id' => end($data['citycode'])]);
                        }
                        if (!empty($data['street_id'])) {
                            $query->where(['street_id' => $data['street_id']]);
                        }
                        if (!empty($data['exception_category'])) {
                            $query->where(['exception_category' => $data['exception_category']]);
                        }
                    }
                )
                ->where(['street_id' => $value['id']])
                ->where(['operation_category' => 2])->count();
            //已处罚标记数量
            $ycfcount      = (clone $this->model)
                ->where(['type' => $this->type])
                ->where(
                    function ($query) use ($data) {
                        if (!empty($data['start_time']) && !empty($data['end_time'])) {
                            $start_time = strtotime($data['start_time']);
                            $end_time   = strtotime($data['end_time']) + 3600 * 24 - 1;
                            $query->whereBetween('create_time', [$start_time, $end_time]);
                        }
                        if (!empty($data['citycode'])) {
                            $query->where(['area_id' => end($data['citycode'])]);
                        }
                        if (!empty($data['street_id'])) {
                            $query->where(['street_id' => $data['street_id']]);
                        }
                        if (!empty($data['exception_category'])) {
                            $query->where(['exception_category' => $data['exception_category']]);
                        }
                    }
                )
                ->where(['street_id' => $value['id']])
                ->where(['operation_category' => 3])->count();
            $newdata[$key] = [
                'name'     => $value['name'],
                'yccount'  => $yccount,
                'zccount'  => $zccount,
                'ycfcount' => $ycfcount
            ];
        }

        return $this->jsonReturn(message('', true, $newdata));
    }

    public function fold_line()
    {
        $date = [strtotime('today'), time()];
        $arr = (clone $this->model)
            ->field('street_id, count(id) total')
            ->with(['street' => function($query) {
                $query->field('id, name');
            }])
            ->where('type', $this->type)
            ->where('street_id', '>', 0)
            ->group('street_id')
            ->whereBetween('create_time', $date)
            ->select();
        $data = [];
        foreach ($arr as $val) {
            $data[] = [
                'name'  => $val->street->name,
                'value' => $val->total
            ];
        }

        return $data;
    }

    /***
     * 基础数据图
     *
     * @return array
     */
    public function foundation()
    {
        //总标记数量
        $count         = (clone $this->model)->where(['type' => $this->type])->count();
        $yesstart_time = strtotime('-1 day');
        $yesend_time   = $yesstart_time + 3600 * 24 - 1;
        $yesdaycount   = (clone $this->model)
            ->where(['type' => $this->type])
            ->whereBetween('create_time', [$yesstart_time, $yesend_time])
            ->count();
        $start_time    = $yesend_time + 1;
        $end_time      = $start_time + 3600 * 24 - 1;
        $todaycount    = (clone $this->model)
            ->where(['type' => $this->type])
            ->whereBetween('create_time', [$start_time, $end_time])
            ->count();
        $cha           = $todaycount - $yesdaycount;
        if ($yesdaycount == 0) {
            $yesdaycount = 1;
        }
        $abs = $cha / $yesdaycount * 100;
        //异常标记数量
        $yccount = (clone $this->model)
            ->where(['type' => $this->type])
            ->where(['operation_category' => 1])->count();
        //正常标记数量
        $zccount = (clone $this->model)
            ->where(['type' => $this->type])
            ->where(['operation_category' => 2])->count();
        //已处罚标记数量
        $ycfcount = (clone $this->model)
            ->where(['type' => $this->type])
            ->where(['operation_category' => 3])->count();
        //巡逻点标记数量
        $xldcount = (clone $this->model)
            ->where(['type' => $this->type])
            ->group('address')->count();
        //巡逻街道标记数量
        $xlqcount = (clone $this->model)
            ->where(['type' => $this->type])
            ->group('street_id')->count();

        return [
            'total_mark'           => $count,
            'patrol_point_count'   => $xldcount,
            'patrol_streets_count' => $xlqcount,
            'abnormal_count'       => $yccount,
            'normal_count'         => $zccount,
            'punished_count'       => $ycfcount,
            'abs'                  => $abs . "%",
            'yesdayCount'          => $yesdaycount,
            'todayCount'           => $todaycount
        ];
    }

    /***
     * 饼图数据
     *
     * @return array[]
     */
    public function cake()
    {
        $date = [strtotime('today'), time()];
        $arr  = (clone (clone $this->model))
            ->field('operation_category, count(id) total')
            ->where('type', $this->type)
            ->whereBetween('create_time', $date)
            ->group('operation_category')
            ->select();
        $data = [];
        foreach ($arr as $val) {
            $data[] = [
                'name'  => $val->getOperationCategoryNameAttr('', $val),
                'value' => $val->total
            ];
        }
        $ysh = (clone (clone $this->model))
            ->where('type', $this->type)
            ->whereBetween('create_time', $date)
            ->where('status', 2)
            ->count();
        if ($ysh) {
            $data[] = [
                'value' => $ysh,
                'name'  => '已审核'
            ];
        }

        return $data;
    }

    // 柱形图数据
    public function column()
    {
        $start_time = strtotime(date('Y-m-d', time())) - $this->day * 3600 * 24;
        $end_time   = $start_time + 3600 * 24 - 1 + $this->day * 3600 * 24;
        /** 异常 **/
        $yc = (clone $this->model)
            ->where(['type' => $this->type])
            ->where(['operation_category' => 1])
            ->whereBetween('create_time', [$start_time, $end_time])
            ->count();
        /** 正常 **/
        $zc = (clone $this->model)
            ->where(['type' => $this->type])
            ->where(['operation_category' => 2])
            ->whereBetween('create_time', [$start_time, $end_time])
            ->count();
        /*** 已处罚***/
        $ycf  = (clone $this->model)
            ->where(['type' => $this->type])
            ->where(['operation_category' => 3])
            ->whereBetween('create_time', [$start_time, $end_time])
            ->count();
        $data=[];
        if(!empty($yc)){
            $data[] =
                [
                    'value' => $yc,
                    'name'  => '异常'
                ];
        }
        if(!empty($zc)){
            $data[] = [
                'value' => $zc,
                'name'  => '正常'
            ];
        }
        if(!empty($zc)){
            $data[] = [
                'value' => $ycf,
                'name'  => '已处罚'
            ];
        }
        if ($this->type == 'illegal') {
            /*** 已审核***/
            $ysh     = (clone $this->model)
                ->where(['type' => $this->type])
                ->where(['status' => 2])
                ->whereBetween('verify_time', [$start_time, $end_time])
                ->count();

            if(!empty($ysh)){
                $data[] = [
                    'value' => $ysh,
                    'name'  => '已审核'
                ];
            }
            $ysc     = (clone $this->model)
                ->where(['type' => $this->type])
                ->whereNotNull('images')
                ->whereBetween('create_time', [$start_time, $end_time])
                ->count();

            if(!empty($ysc)){
                $data[] = [
                    'value' => $ysc,
                    'name'  => '已上传'
                ];
            }
        }

        return $data;
    }
}